//
//  LJPhotoBroserCell.swift
//  LJWeibo
//
//  Created by Raymond on 16/1/4.
//  Copyright © 2016年 liu. All rights reserved.
//

import UIKit

import SDWebImage

import SVProgressHUD

import FLAnimatedImage

let ImageViewMinimumZoomScale:CGFloat = 0.5

class LJPhotoBroserCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            // 清空上一张图片的缓存
            imageView.image = nil
            imageView.animatedImage = nil
            // 清空上一张图片的放大缩小设置
            resetProterties()
            // 判断图片是否已经下载过
            let path = SDWebImageManager.sharedManager().imageCache.defaultCachePathForKey(imageURL!.absoluteString)
            let data = NSData(contentsOfFile: path)
            if data != nil {
                let image = UIImage(data: data!)!
                // 设置图片
                setImage(image, data: data!)
                return
            }
            // 下载图片
            SDWebImageDownloader.sharedDownloader().downloadImageWithURL(imageURL, options: SDWebImageDownloaderOptions(rawValue: 0), progress: { (receive, total) -> Void in
                let progress = Float(receive) / Float(total)
//                print(progress)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    SVProgressHUD.showProgress(progress)
                })
                
                }) { (image, data, error, finished) -> Void in
                    // 菊花开始转
                    // indicator.startAnimating()
                    // 保存图片
                    SDWebImageManager.sharedManager().imageCache.storeImage(image, recalculateFromImage: false, imageData: data, forKey: self.imageURL!.absoluteString, toDisk: true)
                    // 在主线程中设置图片
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.setImage(image, data: data)
                    })
            }
            
//            imageView.sd_setImageWithURL(imageURL) { (image, error, _, _) -> Void in
//                // 关闭菊花
//                self.indicator.stopAnimating()
//                if error != nil {
//                    print("下载图片出错")
//                    return
//                }
//                // 布局imageView的位置
//                self.layoutImageView(image)
//            }
        }
    }
    
    /// 设置图片的方法
    private func setImage(image: UIImage, data: NSData) {
        // 判断是否为gif图片
        let isGif = self.imageURL!.absoluteString.lowercaseString.hasSuffix("gif")
        if isGif {
            // 设置动图
            let animationImage = FLAnimatedImage(animatedGIFData: data)
            self.imageView.animatedImage = animationImage
        }else{
            self.imageView.image = image
        }
        
        // 关闭进度
        SVProgressHUD.dismiss()
        // 布局imageView的位置
        self.layoutImageView(image)
    }
    
    /// 布局imageView的位置
    private func layoutImageView(image: UIImage) {
        let imageSize = displayImageSize(image)
        // 如果图片是小图居中
        if imageSize.height < UIScreen.mainScreen().bounds.height {
            imageView.frame = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
//            imageView.frame = UIScreen.mainScreen().bounds
            // 计算偏移值
            let offsetY = (UIScreen.mainScreen().bounds.height - imageSize.height) * 0.5
            scrollView.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: offsetY, right: 0)
        } else{
            // 长图
            imageView.frame = CGRect(origin: CGPointZero, size: imageSize)
            // 设置contentSize
            scrollView.contentSize = imageSize
        }
    }
    
    /// 计算image的大小
    private func displayImageSize(image: UIImage) -> CGSize {
        let newWidth: CGFloat = UIScreen.mainScreen().bounds.width
        let newheight = newWidth * image.size.height / image.size.width
        return CGSize(width: newWidth, height: newheight)
    }
    
    /// 清空scrollview属性
    private func resetProterties() {
        imageView.transform = CGAffineTransformIdentity
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentSize = CGSizeZero
        scrollView.contentOffset = CGPointZero
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func prepareUI() {
        // scrollView缩放设置
        scrollView.delegate = self
        scrollView.minimumZoomScale = ImageViewMinimumZoomScale
        scrollView.maximumZoomScale = 2.0
        
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        contentView.addSubview(indicator)
        
        // 未获取到图片无法设置图片的大小
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        indicator.translatesAutoresizingMaskIntoConstraints = false
        
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv": scrollView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv": scrollView]))
        
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
    }
    
    //MARK: - 懒加载
    /// scrollView
    private lazy var scrollView: UIScrollView = UIScrollView()
    /// imageView
    private lazy var imageView: LJImageView = LJImageView()
    /// 菊花
    private lazy var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
}

//MARK: - 分类
extension LJPhotoBroserCell: UIScrollViewDelegate {
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    func scrollViewDidZoom(scrollView: UIScrollView) {
        print(scrollView.contentSize)
    }
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        // 缩小结束时移动到中间
        // 获取偏移的值,要不能使用bounds
        var offsetX = (UIScreen.mainScreen().bounds.width - imageView.frame.width) * 0.5
        var offsetY = (UIScreen.mainScreen().bounds.height - imageView.frame.height) * 0.5
        
        offsetX = offsetX < 0 ? 0 : offsetX
        offsetY = offsetY < 0 ? 0 : offsetY
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, 0, 0)
        }
    }
}
